import React from 'react';
import style from './edit.module.less';
import { Button, Form, Input,message } from 'antd';
import { revise } from "@/api/account";
import { useNavigate } from 'react-router-dom';

export default function Edit() {
    const [form] = Form.useForm();
    const navigate = useNavigate();
    // 获取 userId，若不存在则设为空字符串
    let id = sessionStorage.getItem('userId') || '';

    // 确认密码和新密码是否一致的验证规则
    const confirmPasswordValidator = (_, value) => {
        const { newPwd } = form.getFieldValue();
        if (value && newPwd!== value) {
            return Promise.reject('两次输入的密码不一致');
        }
        return Promise.resolve();
    };

    // 验证原密码是否正确
    const confirmPassword = (_, values) => {
        // 获取原密码，若不存在则设为空字符串
        let oldPwd = sessionStorage.getItem('password');
        if (values!== oldPwd) {
            return Promise.reject('原密码错误');
        }
        return Promise.resolve();
    };

    // 修改密码
    const onFinish = async (values) => {
            // 将 id 添加到请求参数中
            const data = { ...values, id };
            const { msg } = await revise(data);
            message.success(msg);
            navigate('/');
    };

    return (
        <div>
            <div className={style.title}>
                修改密码
            </div>
            <Form
                name="wrap"
                form={form}
                labelCol={{ flex: '110px' }}
                labelAlign="left"
                labelWrap
                wrapperCol={{ flex: 1 }}
                colon={false}
                style={{ maxWidth: 600, margin: 20 }}
                // 正确传入 onFinish 函数
                onFinish={onFinish}
            >
                <Form.Item label="原密码" name="oldPwd" rules={[{ required: true, message: '请输入原密码' }, { validator: confirmPassword }]} >
                    <Input />
                </Form.Item>

                <Form.Item label="新密码" name="newPwd" rules={[{ required: true, message: '请输入新密码' }]}>
                    <Input.Password />
                </Form.Item>

                <Form.Item
                    label="确认密码"
                    name="newPwd1"
                    dependencies={['newPwd']}
                    rules={[
                        { required: true, message: '请确认密码' },
                        { validator: confirmPasswordValidator }
                    ]}
                >
                    <Input.Password />
                </Form.Item>
                <Form.Item label=" ">
                    <Button type="primary" htmlType="submit">
                        提交
                    </Button>
                </Form.Item>
            </Form>
        </div>
    );
}
    